import utils.FileUtils;
import utils.SystemLookup;

import java.math.BigInteger;

/**
 * @author dab.
 */
public class BinarySearch {
    private static long elapsedNanoTime = 0;
    private static BigInteger elapsedTime = BigInteger.ZERO;

    public static void main(String[] args) {
        if(args.length != 2) {
            System.out.println("Niepoprawna ilość elementów");
            System.exit(1);
        }
        int searchNumber = 0;
        try {
            searchNumber = Integer.parseInt(args[1]);
        } catch (Exception ex) {
            System.out.println("Niepoprawne dane. Blad parsowania: int");
            System.exit(1);
        }
        String fileName = args[0];

        String[] out = FileUtils.readTextFileLine(SystemLookup.PATH_TO_LOAD + fileName + FileUtils.FILE_EXTENSION).split(" ");
        int[] arrayToSearch = new int[out.length];
        for (int i = 0; i < out.length; i++) {
            arrayToSearch[i] = Integer.parseInt(out[i]);
        }
        System.out.println("Array.lenght: " + arrayToSearch.length);
        //for (int i = 0; i < numberOfExec; i++) {
            //int[] intArray = Arrays.copyOf(arrayToSort, arrayToSort.length);
            long timeStart = System.nanoTime();
            binarySearch(arrayToSearch, searchNumber);
            elapsedNanoTime = System.nanoTime() - timeStart;
            elapsedTime = elapsedTime.add(BigInteger.valueOf(elapsedNanoTime));
        //}
        if(arrayToSearch.length>searchNumber)
            System.out.println(arrayToSearch[searchNumber]);
        System.out.println("\nNano Time: " + elapsedTime.toString());
        System.out.println("Milliseconds Time: " + elapsedTime.divide(new BigInteger("1000000")));

        //int[] tab={1,2,3,4,5,6,8,11,22,33,44,55,66};
        //binarySearch(tab, searchNumber);
    }

    private static void binarySearch(int[] a, int x) {
        int l = 0 , p = a.length - 1, s;
        while (l <= p) {
            s = (l + p) / 2;
            if (a[s] == x) {
                System.out.println("Odnaleziono element " + x + " pod indeksem " + s);
                return;
            }
            if (a[s] < x)
                l = s + 1;
            else
                p = s - 1;
        }
        System.out.println("Nie odnaleziono w tablicy elementu " + x);
    }
}
